<?php
namespace Biz\service\designerAward;

use Biz\model\designerAward\User as mUser;
use Biz\model\designerAward\Sign as mSign;
use Doraemon\model\Member as mMember;
use Doraemon\service\User as sUser;
use Doraemon\model\DesignerAuth as mDesignerAuth;
use Doraemon\model\ArticleHouse as mArticleHouse;
use Doraemon\model\Article as mArticle;
use Doraemon\model\Photos as mPhotos;
use Doraemon\model\MemberExtendInfo;
use Doraemon\service\Article as sArticle;
use Doraemon\tools\ImgUrl;
use Doraemon\model\DesignerCompetitionProduct as mDesignerCompetitionProduct;
use Doraemon\tools\Area;
use Biz\tools\ShopArea;

/**
 * @deprecated
 */
class Main
{
    const MAX_NUM = 15;
    const MAX_NUM_HOUSE = 5;
    /**
     * 用户信息保存（分个人还是机构）
     */
    public static function addUser($params, $member = []){
        $data = [];
        $error = '';
        if(empty($member)) {
            $member = sUser::getUserInfo($params['uid']);
        }

        //需要判断入口用户是否已报名
        $sign = mSign::getOneByWhere(['uid' => $params['uid']],'id');
        $user = mUser::getOneByWhere(['uid'=> $params['uid']],'types');
        if($sign) {
            if($user == mUser::USER_TYPE_DESIGNER && $params['types']!=mUser::USER_TYPE_DESIGNER){
                $error = '用户只能报设计师通道';
            }else if($user == mUser::USER_TYPE_OWNER && $params['types']!=mUser::USER_TYPE_OWNER){
                $error = '用户只能报业主通道';
            }
        }

        if(!empty($error)){
            //用户入口错误，直接报错
            $result['error'] = $error;
            return $result;
        }else{
            if($user){
                if($user == mUser::USER_TYPE_DESIGNER && $params['types'] == mUser::USER_TYPE_OWNER){
                    //从业主入口进来时，覆盖之前的信息
                    $data = [
                        'uid' => $member['uid'],
                        'name' => $member['nick'],
                        //'sex' => $member['gender'],
                        'award_name' => '',
                        'address' => '',
                        'phone' => '',
                        'cards' => '',
                        'cards_front' => '',
                        'cards_back' => '',
                        'descrip' => '',
                        'company_name' => '',
                        'company_license' => '',
                        'company_leader' => '',
                        'company_address' => '',
                        'company_logo' => '',
                        'company_descrip' => '',
                        'company_phone' => '',
                        'types' => mUser::USER_TYPE_OWNER
                    ];
                    $result = mUser::updateData($data,['uid'=> $member['uid']]);
                    //记录日志
                    \Doraemon\tools\Log::debug('设计师奖-用户信息更新', json_encode($params, true));
                }
            }else{
                //用户第一次进来
                if($params['types'] == mUser::USER_TYPE_OWNER){
                    //业主
                    $data = [
                        'uid' => $member['uid'],
                        'name' => $member['nick'],
                        //'sex' => $member['gender'],
                        'types' => mUser::USER_TYPE_OWNER
                    ];
                }else{
                    if($member['type'] == mMember::AUTH_USER_DESIGNER) {
                        //认证设计师
                        $designer = mDesignerAuth::getByUId($params['uid']);
                        if($designer){
                            $data = [
                                'uid' => $member['uid'],
                                'name' => $designer['real_name'],
                                'award_name' => $designer['real_name'],
                                //'sex' => $member['gender'],
                                'address' => $member['area'],
                                'phone' => $designer['phone'],
                                'cards_front' => $designer['front_card_pic'],
                                'cards_back' => $designer['reverse_card_pic'],
                                'types' => mUser::USER_TYPE_DESIGNER
                            ];
                        }else{
                            $result['error'] = '抱歉，账号是未认证设计师，不能报名设计师通道';
                            return $result;
                        }
                    }else{
                        if($params['company_name']<>'') {
                            //机构
                            $data = [
                                'uid' => $params['uid'],
                                'award_name' => isset($params['award_name'])?$params['award_name']:'',
                                'company_name' => $params['company_name'],
                                'company_license' => $params['company_license'],
                                'company_leader' => $params['company_leader'],
                                'company_address' => $params['company_address'],
                                'company_logo' => $params['company_logo'],
                                'company_descrip' => $params['company_descrip'],
                                'company_phone' => $params['company_phone'],
                                'types' => mUser::USER_TYPE_DESIGNER
                            ];
                        }else{
                            //个人
                            $data = [
                                'uid' => $params['uid'],
                                'name' => $params['name'],
                                'award_name' => isset($params['award_name'])?$params['award_name']:'',
                                //'sex' => $params['sex'],
                                'address' => $params['address'],
                                'phone' => $params['phone'],
                                'cards' => isset($params['cards'])?$params['cards']:'',
                                'cards_front' => $params['cards_front'],
                                'cards_back' => $params['cards_back'],
                                'descrip' => $params['descrip'],
                                'types' => mUser::USER_TYPE_DESIGNER
                            ];
                        }
                    }
                }

                $time = date('Y-m-d H:i:s');
                $data['add_time'] = $time;

                $result = mUser::addData($data);
                //记录日志
                \Doraemon\tools\Log::debug('设计师奖-用户信息保存', json_encode($params, true));
            }
        }

        return $result;
    }

    /**
     * 获取用户的信息
     * @param $uid
     * @return array
     */
    public static function getUser($uid){
        $data = [
            //'areas_data'=> mUser::USER_ARAE,
            'house_data'=> mSign::USER_HOUSE,
        ];
        $user = mUser::getOneByWhere(['uid'=>$uid]);
        if($user){
            if(!empty($user['areas'])){
                $user['areas_data'] = ShopArea::locationId2String($user['areas']);
            }
            $data['user_info'] = $user;
        }else{
            $data['user_info'] = NULL;
        }
        //业主报名后不可报名设计师，相反一样的逻辑
        $sign = mSign::getoneByWhere(['uid'=>$uid, 'ORDER'=>['id'=>'DESC']]);
        if($sign){
            $case = sArticle::getArticle($sign['aid']);
            $data['user_sign'] = [
                'title'=> $case['title'],
                'house'=> $sign['house'],
                'add_time'=> $sign['add_time'],
            ];
        }else{
            $data['user_sign'] = NULL;
        }
        //总报名数量是否达到报名上限15
        $data['total'] = self::MAX_NUM - mSign::count(['uid'=>$uid]);
        return $data;
    }

    /**
     * 用户报名
     */
    public static function addSign($params){
        $error = '';
        $result = mSign::action(function()use($params){
            $member = sUser::getUserInfo($params['uid']);
            $user = mUser::getOneByWhere(['uid'=>$params['uid']],['areas','types', 'area']);
            //如果用户是设计师入口且非认证设计师，没有保存用户信息，不能报名
            if(empty($user) &&
                isset($params['types']) && $params['types'] == mUser::USER_TYPE_DESIGNER &&
                in_array($member['type'], [mMember::USER_COMMON, mMember::AUTH_USER_V, mMember::AUTH_USER_UNAUTH_DESIGNER])
            ){
                $error = '用户信息不能空';
                return [
                    'error'=> $error,
                    'data'=> false,
                ];
            }

            $sign = mSign::getAllByWhere(['uid'=>$params['uid']]);
            if(empty($sign) || (!empty($sign) && count($sign) < self::MAX_NUM) ) {
                //已经报名的案例不能再参加报名
                if(!empty($sign) && in_array($params['house_case'],array_column($sign, 'aid'))){
                    $error = '案例不能重复参加报名';
                    return [
                        'error'=> $error,
                        'data'=> false,
                    ];
                }

                if(!empty($user) && $user['types'] == mUser::USER_TYPE_OWNER && !empty($sign)){
                    //业主只能报一套案例
                    $error = '报名名额已达上限';
                    return [
                        'error'=> $error,
                        'data'=> false,
                    ];
                }

                $sign_house_max = self::getSign($sign);
                //判断哪个户型报名达到上限后了，不能再报这个户型
                if(!isset($sign_house_max[$params['house_type']])) {
                    //可以继续报名
                    $data = [
                        'uid' => $params['uid'],
                        'house' => $params['house_type'],
                        'aid' => $params['house_case'],
                        'descrip' => isset($params['descrip']) ? $params['descrip'] : '',
                        'crown_award' => isset($params['crown_award']) ? $params['crown_award'] : '',
                        'area' => AdmDesignerAward::getArea(explode(',', $params['areas'])), // 根据地区获取赛区信息
                        'add_time' => date('Y-m-d H:i:s')
                    ];

                    //如果是业主和认证设计师需要走addUser
                    if((isset($params['types']) && $params['types'] == mUser::USER_TYPE_OWNER) || $member['type'] == mMember::AUTH_USER_DESIGNER){
                        $adduser =self::addUser($params, $member);
                        if(!isset($adduser['error'])){
                            $result = mSign::addData($data);
                        }else{
                            $error = $adduser['error'];
                            return [
                                'error'=> $error,
                                'data'=> false,
                            ];
                        }
                    }else{
                        $result = mSign::addData($data);
                    }

                    //更新赛区
                    if($result) {
                        $result = mUser::updateData(
                            ['areas' => $params['areas']],
                            ['uid' => $params['uid']]
                        );
                    }

                    if ($result) {
                        //报名成功，app下行通知（你好，你的作品{案例标题}已经成功报名XX赛区XX户型，感谢你的支持）
                        if($params['types'] == mUser::USER_TYPE_DESIGNER){
                            $award_name = '「营造家奖」';
                        }else{
                            $award_name = '营造家奖「年度业主推荐奖」';
                        }
                        \Doraemon\cache\Queue::insertQueue('queue/Sysmsg/Send', [
                            'msgCode' => 601,
                            'to_uid' => $params['uid'],
                            'msgParams' => [
                                'award_name'=> $award_name,
                            ]
                        ], \Doraemon\cache\Queue::QUEUE_DORAEMON);
                        //记录日志
                        \Doraemon\tools\Log::debug('设计师奖-用户报名成功', 'save:'.json_encode($data, true).'; post:'.json_encode($params, true));
                        return [
                            'error'=> '',
                            'data'=> true,
                        ];
                    } else {
                        $error = '报名失败，请稍后重试';
                        return [
                            'error'=> $error,
                            'data'=> false,
                        ];
                    }
                }else{
                    //某个户型报名名额已达上限
                    $error = '该户型报名名额已达上限';
                    return [
                        'error'=> $error,
                        'data'=> false,
                    ];
                }

            }else if(count($sign) >= self::MAX_NUM){
                //15套案例已达上限
                $error = '报名名额已达上限';
                return [
                    'error'=> $error,
                    'data'=> false,
                ];
            }
        });
        return $result;
    }

    private static function getSign($sign, $all = false){
        $sign_house = $sign_house_max = [];
        if($sign){
            foreach($sign as $_k=>&$_v){
                $sign_house[$_v['house']][] = $_v;
            }
            foreach($sign_house as $_key=>&$_val){
                if(count($_val) == self::MAX_NUM_HOUSE ) {
                    $sign_house_max[$_key] = count($_val);
                }else if($all){
                    $sign_house_max[$_key] = array_column($_val, 'aid');
                }
            }
        }
        return $sign_house_max;

    }


    /**
     * 获取用户案例
     * @param $param
     * @return array
     */
    public static function getCases($param){
        $uid = $param['uid'];

        $result = [];
        //获取案例信息
        $result = sArticle::getFormatArticleToAwardByUid($uid);

        if(!empty($result)){
            //获取案例户型报名数量
            $sign = mSign::getAllByWhere(['uid'=>$uid]);
            if(!empty($sign)) {
                $sign = self::getSign($sign, true);
            }

            $result = array_map(function($_case)use($sign, $param) {
                $_case['case_max'] = false;
                $_case['case_use'] = false;
                $_case['case_history'] = false;
                $_case['case_invalid'] = false;
                $_case['case_designer'] = false;
                $_case['is_grey'] = false;

                //如果是业主，案例必须关联设计师，未关联true
                if(isset($param['types']) &&
                    $param['types'] == mUser::USER_TYPE_OWNER &&
                    empty($_case['designer_uid']))
                {
                    $_case['case_designer'] = true;
                }

                //是否参加历史参赛，参加了true
                if($_case['is_join_passed_award']<>0){
                    $_case['case_history'] = true;
                }

                //2017年7月10日前生产的案例，是过期案例
                if($_case['publish_time'] < strtotime('2017-07-10')){
                    $_case['case_invalid'] = true;
                }

                //当前案例是否达到报名名额上限,案例是否已经提交报名过
                if(!empty($sign)) {
                    if ($_case['house_size'] <= 60) {
                        if(isset($param['size']) && $param['size']>0 && $param['size'] <= 60) {
                            $_case['check_size'] = true;
                        }
                        if(isset($sign[mSign::USER_HOUSE_SAMLL])){
                            if(is_integer($sign[mSign::USER_HOUSE_SAMLL])) {
                                $_case['case_max'] = true;
                            }
//                            else if(is_array($sign[mSign::USER_HOUSE_SAMLL]) && in_array($_case['aid'], $sign[mSign::USER_HOUSE_SAMLL])){
//                                $_case['case_use'] = true;
//                            }
                        }
                    } else if ($_case['house_size'] > 60 && $_case['house_size'] <= 150) {
                        if(isset($sign[mSign::USER_HOUSE_MIDDEL])){
                            if(is_integer($sign[mSign::USER_HOUSE_MIDDEL])) {
                                $_case['case_max'] = true;
                            }
//                            else if(is_array($sign[mSign::USER_HOUSE_MIDDEL]) && in_array($_case['aid'], $sign[mSign::USER_HOUSE_MIDDEL])){
//                                $_case['case_use'] = true;
//                            }
                        }
                    } else if ($_case['house_size'] > 150) {
                        if(isset($sign[mSign::USER_HOUSE_BIG])){
                            if(is_integer($sign[mSign::USER_HOUSE_BIG])) {
                                $_case['case_max'] = true;
                            }
//                            else if(is_array($sign[mSign::USER_HOUSE_BIG]) && in_array($_case['aid'], $sign[mSign::USER_HOUSE_BIG])){
//                                $_case['case_use'] = true;
//                            }
                        }
                    }
                    foreach($sign as $_sign){
                        if(is_array($_sign) && in_array($_case['aid'], $_sign)){
                            $_case['case_use'] = true;
                            break;
                        }
                    }
                }

                //是否变灰
                if($_case['case_max'] ||
                    $_case['case_use'] ||
                    $_case['case_history'] ||
                    $_case['case_invalid'] ||
                    $_case['case_designer']
                ){
                    $_case['is_grey'] = true;
                }else{
                    //是否属于当前户型
                    if(isset($param['size']) && $param['size']>0){
                        $_case['is_grey'] = true;

                        if($_case['house_size'] <= 60 && $param['size'] <= 60){
                            $_case['is_grey'] = false;
                        }else if($param['size'] > 60 && $param['size'] <= 150 && $_case['house_size'] > 60 && $_case['house_size']<=150){
                            $_case['is_grey'] = false;
                        }else if($_case['house_size'] > 150 && $param['size'] > 150){
                            $_case['is_grey'] = false;
                        }
                    }
                }

                return $_case;
            }, $result);
        }

        return $result;
    }

    /**
     * 获取用户案例【作废】
     */
    public static function getCases2($param){
        $uid = $param['uid'];

        $sign = mSign::getAllByWhere(['uid'=>$uid]);
        if(!empty($sign)) {
            $sign = self::getSign($sign, true);
        }

        //营造家获奖,表示是否参加过设计师奖
        $sigin_2018 = mDesignerCompetitionProduct::getAidsOfAward2018();

        $where = [];
        if(isset($param['size']) && $param['size']>0){
            if($param['size'] <= 60){
                $where['house_size[<=]'] = 60;
            }else if($param['size'] > 60 && $param['size'] <= 150){
                $where['house_size[<>]'] = [61, 150];
            }else{
                $where['house_size[>]'] = 150;
            }
        }

        $data = [];
        //获取文章
        $case = mArticle::getArticleByUid($uid);
        if($case){
            try{
                //获取用户的案例房屋信息 area（位置） house_size（大小）house_construction（结构）house_stuff（装修费）designer（1 都表示没有请设计师。 2表示请了设计师）
                if(empty($where)) {
                    $house = mArticleHouse::getArticleHouseByIds(array_column($case, 'aid'));
                }else{
                    $where['aid'] = array_column($case, 'aid');
                    $house = mArticleHouse::select('*', $where);
                }
                if($house) {
                    $house = array_column($house, NULL, 'aid');
                }

                //获取文章图片
                $photos = [];
                //$photos = mPhotos::getPhotosByFilter($uid, ['article_id'=>array_column($case, 'aid')]);

                $case = array_map(function($_case)use($house, $photos, $sign){
                    $_case['case_max'] = false;
                    $_case['case_use'] = false;
                    $_case['case_history'] = false;
                    $_case['case_invalid'] = false;
                    $_case['is_grey'] = false;

                    //是否参加历史参赛
                    if(!empty($sigin_2018) && in_array($_case['aid'], $sigin_2018)){
                        $_case['case_history'] = true;
                    }
                    //2017年7月10日前生产的案例，表示是否过期案例
                    if($_case['addtime'] < strtotime('2017-07-10')){
                        $_case['case_invalid'] = true;
                    }
                    if(!empty($_case['cover_pic_id'])){
                        $_case['cover_pic_url'] = ImgUrl::getUrl(ImgUrl::APPTYPE_APP, $_case['cover_pic_id'], ImgUrl::IMAGE_SIZE_A_PIC);
                    }
                    if(!empty($house) && isset($house[$_case['aid']])){
                        $_case['house'] = $house[$_case['aid']];
                        //当前案例是否达到报名名额上限,案例是否已经提交报名过
                        if(!empty($sign)) {
                            if ($house[$_case['aid']]['house_size'] <= 60) {
                                if(isset($sign[mSign::USER_HOUSE_SAMLL])){
                                    if(is_integer($sign[mSign::USER_HOUSE_SAMLL])) {
                                        $_case['case_max'] = true;
                                    }else if(is_array($sign[mSign::USER_HOUSE_SAMLL]) && in_array($_case['aid'], $sign[mSign::USER_HOUSE_SAMLL])){
                                        $_case['case_use'] = true;
                                    }
                                }
                            } else if ($house[$_case['aid']]['house_size'] > 60 && $house[$_case['aid']]['house_size'] <= 150) {
                                if(isset($sign[mSign::USER_HOUSE_MIDDEL])){
                                    if(is_integer($sign[mSign::USER_HOUSE_MIDDEL])) {
                                        $_case['case_max'] = true;
                                    }else if(is_array($sign[mSign::USER_HOUSE_MIDDEL]) && in_array($_case['aid'], $sign[mSign::USER_HOUSE_MIDDEL])){
                                        $_case['case_use'] = true;
                                    }
                                }
                            } else if ($house[$_case['aid']]['house_size'] > 150) {
                                if(isset($sign[mSign::USER_HOUSE_BIG])){
                                    if(is_integer($sign[mSign::USER_HOUSE_BIG])) {
                                        $_case['case_max'] = true;
                                    }else if(is_array($sign[mSign::USER_HOUSE_BIG]) && in_array($_case['aid'], $sign[mSign::USER_HOUSE_BIG])){
                                        $_case['case_use'] = true;
                                    }
                                }
                            }
                        }

//                        if(!empty($photos)){
//                            foreach($photos as $_k=>&$_v){
//                                if($_v['article_id'] == $_case['aid']){
//                                    $_case['photos'][$_case['aid']][] = $_v;
//                                }
//                            }
//                        }
                    }

                    //是否变灰
                    if($_case['case_max'] || $_case['case_use'] ||  $_case['case_history'] || $_case['case_invalid']){
                        $_case['is_grey'] = true;
                    }
                    return $_case;
                },$case);

                //获取案例
                $data['data'] = $case;
            }catch (Exception $e){
                $data['data'] = $e;
            }

        }else{
            $data['data'] = [];
        }

        //print_r('<pre>');print_r($data);die('<=======>');
        return  $data;
    }

}